<?php

namespace app\admin\controller\user;

use app\admin\model\activity\Order;
use app\admin\model\UserDeliveryAddress;
use app\admin\model\withdraw\Way;
use app\common\controller\Backend;
use app\common\library\Auth;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $rows = $list->items();
            $rows = array_map(function ($e) {
                $e = $e->toArray();
                $e['order_num'] = Order::where('buy_id', $e['id'])->count();
                return $e;
            }, $rows);
            $result = array("total" => $list->total(), "rows" => $rows);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        $this->modelSceneValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    public function deliveryaddress()
    {
        $userId = $this->request->get('user_id');
        $delivery = UserDeliveryAddress::where('user_id', $userId)->find();
        $row = [
            'delivery_name' => '',
            'delivery_phone' => '',
            'delivery_district' => '',
            'delivery_address' => '',
        ];
        if ($delivery) {
            $row = array_merge($row, $delivery->toArray());
        }
        if ($this->request->isPost()) {
            $row = $this->request->post('row/a');
            $delivery = UserDeliveryAddress::where('user_id', $userId)->find();
            if ($delivery) {
                $delivery->delivery_name = $row['delivery_name'];
                $delivery->delivery_phone = $row['delivery_phone'];
                $delivery->delivery_district = $row['delivery_district'];
                $delivery->delivery_address = $row['delivery_address'];
                $delivery->save();
            } else {
                UserDeliveryAddress::create([
                    'user_id' => $userId,
                    'delivery_name' => $row['delivery_name'],
                    'delivery_phone' => $row['delivery_phone'],
                    'delivery_district' => $row['delivery_district'],
                    'delivery_address' => $row['delivery_address'],
                    'createtime' => time(),
                    'updatetime' => time(),
                ]);
            }

            $this->success("保存成功");
        }
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    public function setmerchant()
    {
        $userId = $this->request->get('user_id');
        $user = \app\admin\model\User::get($userId);
        if ($this->request->isPost()) {
            $shopEndTime = $this->request->post('shop_end_time');
            $user->is_shop = 1;
            $user->shop_end_time = $shopEndTime;
            $user->save();

            $this->success("保存成功");
        }

        $this->view->assign('shop_end_time', $user->shop_end_time);
        return $this->view->fetch();
    }

}
